<template>
  <div class="knowledge-management">
    <div class="page-header">
      <h2>农业知识管理</h2>
      <button class="btn primary-btn" @click="showAddModal = true">
        <i class="fas fa-plus"></i> 发布新知识
      </button>
    </div>

    <!-- 知识分类筛选 -->
    <div class="category-filter">
      <button 
        :class="{ active: selectedCategory === 'all' }"
        @click="selectedCategory = 'all'"
        class="category-btn"
      >
        查看全部
      </button>
      <button 
        v-for="category in categories" 
        :key="category.id"
        :class="{ active: selectedCategory === category.id }"
        @click="selectedCategory = category.id"
        class="category-btn"
      >
        {{ category.name }}
      </button>
    </div>

    <!-- 知识列表 -->
    <div class="knowledge-list">
      <div v-for="knowledge in filteredKnowledge" :key="knowledge.id" class="knowledge-card">
        <div class="knowledge-header">
          <span class="knowledge-category">{{ getCategoryName(knowledge.categoryId) }}</span>
          <span class="knowledge-date">{{ knowledge.date }}</span>
          <div class="knowledge-actions">
            <button class="icon-btn" @click="editKnowledge(knowledge)">
              <i class="fas fa-edit"></i>
            </button>
            <button class="icon-btn delete-btn" @click="deleteKnowledge(knowledge.id)">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
        <h3 class="knowledge-title">{{ knowledge.title }}</h3>
        <div v-if="knowledge.image" class="knowledge-image">
          <img :src="knowledge.image" :alt="knowledge.title" class="knowledge-img" />
        </div>
        <!-- 新增summary区域 -->
        <div class="knowledge-summary">
          <p>{{ knowledge.summary }}</p>
        </div>
        <div class="knowledge-footer">
          <div class="knowledge-stats">
            <span><i class="fas fa-eye"></i> {{ knowledge.views }}</span>
            <span><i class="fas fa-heart"></i> {{ knowledge.likes }}</span>
          </div>
          <!-- 新增阅读全文按钮 -->
          <button class="read-more-btn" @click="showDetail(knowledge)">
            阅读全文
          </button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="filteredKnowledge.length === 0" class="empty-state">
      <div class="empty-icon">📚</div>
      <h3>暂无农业知识</h3>
      <p>点击"发布新知识"添加您的专业知识</p>
    </div>

    <!-- 添加/编辑知识模态框 -->
    <div v-if="showAddModal || showEditModal" class="modal-overlay">
      <div class="modal">
        <h3>{{ showAddModal ? '发布新知识' : '编辑知识' }}</h3>
        <form @submit.prevent="submitKnowledge">
          <div class="form-group">
            <label>标题 <span class="required">*</span></label>
            <input type="text" v-model="currentKnowledge.title" required placeholder="请输入知识标题">
          </div>
          <div class="form-group">
            <label>分类 <span class="required">*</span></label>
            <select v-model="currentKnowledge.categoryId" required>
              <option value="">请选择分类</option>
              <option v-for="category in categories" :key="category.id" :value="category.id">
                {{ category.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>图片上传</label>
            <div class="image-upload-area" @click="triggerFileInput" :class="{ 'has-image': currentKnowledge.image }">
              <input 
                type="file" 
                ref="fileInput"
                accept="image/*" 
                @change="handleImageUpload" 
                style="display: none;"
              />
              <div v-if="!currentKnowledge.image" class="upload-placeholder">
                <i class="fas fa-cloud-upload-alt"></i>
                <p>点击上传图片</p>
                <span>支持 JPG、PNG 格式，最大 5MB</span>
              </div>
              <div v-else class="image-preview">
                <img :src="currentKnowledge.image" alt="预览" />
                <button type="button" class="remove-image-btn" @click.stop="removeImage">
                  <i class="fas fa-times"></i>
                </button>
              </div>
            </div>
          </div>
          <!-- 新增summary输入框 -->
          <div class="form-group">
            <label>摘要 <span class="required">*</span></label>
            <textarea v-model="currentKnowledge.summary" rows="3" required placeholder="请输入知识摘要"></textarea>
          </div>
          <div class="form-group">
            <label>内容 <span class="required">*</span></label>
            <textarea v-model="currentKnowledge.content" rows="6" required placeholder="请输入知识内容"></textarea>
          </div>
          <div class="modal-actions">
            <button type="button" class="btn secondary-btn" @click="closeModal">取消</button>
            <button type="submit" class="btn primary-btn">
              {{ showAddModal ? '发布' : '更新' }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 知识详情弹窗 -->
    <el-dialog
      v-model="showDetailModal"
      :title="currentDetail.title"
      width="70%"
      top="5vh"
      class="knowledge-detail-dialog"
    >
      <div class="detail-header">
        <div class="detail-meta">
          <span class="detail-category">{{ getCategoryName(currentDetail.categoryId) }}</span>
          <span class="detail-date">{{ currentDetail.date }}</span>
          <div class="detail-stats">
            <span><i class="fas fa-eye"></i> {{ currentDetail.views }}</span>
            <span><i class="fas fa-heart"></i> {{ currentDetail.likes }}</span>
          </div>
        </div>
      </div>
      
      <div class="detail-content">
        <div v-if="currentDetail.image" class="detail-image">
          <img :src="currentDetail.image" :alt="currentDetail.title" />
        </div>
        
        <div class="detail-summary">
          <h4>内容摘要</h4>
          <p>{{ currentDetail.summary }}</p>
        </div>
        
        <div class="detail-full-content">
          <h4>详细内容</h4>
          <div v-html="currentDetail.content"></div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDetailModal = false">关闭</el-button>
          <el-button type="primary" @click="showDetailModal = false">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElDialog, ElButton, ElMessageBox } from 'element-plus'
import { ElMessage } from 'element-plus'

// 响应式数据
const categories = ref([
  { id: 1, name: '种植技术' },
  { id: 2, name: '病虫害防治' },
  { id: 3, name: '养殖技术' },
  { id: 4, name: '农业机械' },
  { id: 5, name: '市场分析' }
])

const knowledgeList = ref([
  {
    id: 1,
    title: '西红柿高产种植技术要点',
    summary: '详细介绍西红柿从育苗到收获的全过程技术要点，包括土壤准备、施肥管理、病虫害防治等关键环节。',
    content: `
      <h3>一、土壤准备</h3>
      <p>选择排水良好、富含有机质的沙壤土，pH值在6.0-6.8之间...</p>
      
      <h3>二、育苗技术</h3>
      <p>选用优质种子，在温室内进行育苗，保持适宜的温度和湿度...</p>
      
      <h3>三、田间管理</h3>
      <p>合理密植，及时整枝打杈，保证通风透光...</p>
      
      <h3>四、病虫害防治</h3>
      <p>主要防治早疫病、晚疫病、白粉病等常见病害...</p>
    `,
    categoryId: 1,
    date: '2024/1/20',
    views: 1561,
    likes: 128,
    image: 'https://images.unsplash.com/photo-1592924357228-91a4daadcfea?w=400&h=250&fit=crop'
  },
  {
    id: 2,
    title: '黄瓜常见病虫害识别与防治',
    summary: '全面解析黄瓜生长过程中常见的病虫害监测方法，提供科学的防治方案。',
    content: '全面解析黄瓜生长过程中常见的病虫害监测方法，提供科学的防治方案。详细内容包括...',
    categoryId: 2,
    date: '2024/1/19',
    views: 1280,
    likes: 96,
    image: 'https://images.unsplash.com/photo-1540420773420-3366772f4999?w=400&h=250&fit=crop'
  },
  {
    id: 3,
    title: '现代化农业机械使用指南',
    summary: '介绍各类现代化农业机械的使用方法、维护保养要点，提高农业生产效率。',
    content: '介绍各类现代化农业机械的使用方法、维护保养要点，提高农业生产效率。详细内容包括...',
    categoryId: 4,
    date: '2024/1/18',
    views: 980,
    likes: 75,
    image: 'https://images.unsplash.com/photo-1589923188651-268a35c0d0bf?w=400&h=250&fit=crop'
  }
])

const selectedCategory = ref('all')
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDetailModal = ref(false)
const fileInput = ref(null)

const currentKnowledge = ref({
  id: null,
  title: '',
  summary: '',
  content: '',
  categoryId: '',
  image: ''
})

const currentDetail = ref({
  id: null,
  title: '',
  summary: '',
  content: '',
  categoryId: '',
  date: '',
  views: 0,
  likes: 0,
  image: ''
})

// 计算属性
const filteredKnowledge = computed(() => {
  if (selectedCategory.value === 'all') {
    return knowledgeList.value
  }
  return knowledgeList.value.filter(k => k.categoryId === parseInt(selectedCategory.value))
})

// 方法
const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未知分类'
}

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      alert('请上传图片文件！')
      return
    }
    
    // 检查文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
      alert('图片大小不能超过 5MB！')
      return
    }
    
    const reader = new FileReader()
    reader.onload = (e) => {
      currentKnowledge.value.image = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

const removeImage = () => {
  currentKnowledge.value.image = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

const editKnowledge = (knowledge) => {
  currentKnowledge.value = { ...knowledge }
  showEditModal.value = true
}

const deleteKnowledge = (id) => {
  ElMessageBox.confirm(
    '确定要删除这条知识吗？',
    '提示',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
  ).then(() => {
    // 删除成功
    knowledgeList.value = knowledgeList.value.filter(k => k.id !== id)
    ElMessage.success('删除成功')
  }).catch(() => {
    // 删除取消
  })
}

const showDetail = (knowledge) => {
  currentDetail.value = { ...knowledge }
  showDetailModal.value = true
}

const submitKnowledge = () => {
  if (showAddModal.value) {
    // 添加新知识
    const newKnowledge = {
      ...currentKnowledge.value,
      id: Date.now(),
      date: new Date().toLocaleDateString('zh-CN'),
      views: 0,
      likes: 0
    }
    knowledgeList.value.unshift(newKnowledge)
  } else {
    // 更新知识
    const index = knowledgeList.value.findIndex(k => k.id === currentKnowledge.value.id)
    if (index !== -1) {
      knowledgeList.value[index] = { ...currentKnowledge.value }
    }
  }
  closeModal()
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  currentKnowledge.value = {
    id: null,
    title: '',
    summary: '',
    content: '',
    categoryId: '',
    image: ''
  }
  removeImage()
}

onMounted(() => {
  // 可以在这里加载专家知识数据
})
</script>

<style scoped>
.knowledge-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.category-filter {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.category-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.category-btn.active {
  background: #4CAF50;
  color: white;
  border-color: #4CAF50;
}

.knowledge-list {
  display: grid;
  gap: 20px;
}

.knowledge-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  border-left: 4px solid #4CAF50;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.knowledge-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.15);
}

.knowledge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.knowledge-category {
  background: #E8F5E9;
  color: #2E7D32;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.knowledge-date {
  color: #666;
  font-size: 14px;
}

.knowledge-actions {
  display: flex;
  gap: 10px;
}

.icon-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 5px;
  color: #666;
  transition: color 0.3s;
}

.icon-btn:hover {
  color: #4CAF50;
}

.delete-btn:hover {
  color: #f44336;
}

.knowledge-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  line-height: 1.4;
}

.knowledge-image {
  margin: 15px 0;
  border-radius: 8px;
  overflow: hidden;
}

.knowledge-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-radius: 6px;
}

/* 新增summary样式 */
.knowledge-summary {
  background: #f9f9f9;
  padding: 12px 15px;
  border-radius: 6px;
  margin: 15px 0;
  border-left: 3px solid #4CAF50;
}

.knowledge-summary p {
  color: #555;
  font-size: 14px;
  line-height: 1.5;
  margin: 0;
}

.knowledge-content {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  display: -webkit-box;
  line-clamp: 3;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.knowledge-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.knowledge-stats {
  display: flex;
  gap: 15px;
  color: #999;
  font-size: 14px;
}

.knowledge-stats i {
  margin-right: 5px;
}

/* 新增阅读全文按钮样式 */
.read-more-btn {
  background: transparent;
  color: #4CAF50;
  border: 1px solid #4CAF50;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.read-more-btn:hover {
  background: #4CAF50;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  opacity: 0.5;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  padding: 30px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}

.modal h3 {
  margin-bottom: 25px;
  color: #333;
  text-align: center;
  font-size: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.required {
  color: #f44336;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
  font-family: inherit;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}

/* 图片上传区域 */
.image-upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.image-upload-area:hover {
  border-color: #4CAF50;
  background: #f8fff8;
}

.image-upload-area.has-image {
  border-style: solid;
  border-color: #4CAF50;
  background: white;
  padding: 15px;
}

.upload-placeholder {
  color: #666;
}

.upload-placeholder i {
  font-size: 48px;
  color: #ccc;
  margin-bottom: 10px;
}

.upload-placeholder p {
  margin: 10px 0 5px;
  font-weight: 600;
}

.upload-placeholder span {
  font-size: 12px;
  color: #999;
}

.image-preview {
  position: relative;
  display: inline-block;
}

.image-preview img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 6px;
}

.remove-image-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  border: none;
  border-radius: 50%;
  background: #f44336;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s;
  min-width: 80px;
}

.primary-btn {
  background: #4CAF50;
  color: white;
}

.primary-btn:hover {
  background: #45a049;
  transform: translateY(-1px);
}

.secondary-btn {
  background: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}

.secondary-btn:hover {
  background: #e9e9e9;
}

/* 知识详情弹窗样式 */
.detail-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.detail-category {
  background: #E8F5E9;
  color: #2E7D32;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 600;
}

.detail-date {
  color: #666;
  font-size: 14px;
}

.detail-stats {
  display: flex;
  gap: 15px;
  color: #999;
  font-size: 14px;
}

.detail-stats i {
  margin-right: 5px;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.detail-image {
  margin-bottom: 20px;
  text-align: center;
}

.detail-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
}

.detail-summary {
  background: #f9f9f9;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
  border-left: 3px solid #4CAF50;
}

.detail-summary h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
}

.detail-summary p {
  margin: 0;
  color: #555;
  line-height: 1.5;
}

.detail-full-content h4 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #333;
}

.detail-full-content :deep(h3) {
  color: #4CAF50;
  margin-top: 20px;
  margin-bottom: 10px;
}

.detail-full-content :deep(p) {
  line-height: 1.6;
  margin-bottom: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .category-filter {
    justify-content: flex-start;
  }
  
  .modal {
    margin: 20px;
    padding: 20px;
  }
  
  .modal-actions {
    flex-direction: column;
  }
  
  .btn {
    width: 100%;
  }
  
  .knowledge-footer {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
  
  .detail-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>